package com.sr.security.handler;

import com.sr.constant.Constant;
import com.sr.enums.ResponseCode;
import com.sr.security.filter.LoginUserFilter;
import com.sr.util.JwtTokenUtil;
import com.sr.util.R;
import com.sr.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xiaochi
 * @date 2022/5/2 17:56
 * @desc LogoutHandler 退出成功处理器
 */
@Slf4j
public class LogoutHandler implements LogoutSuccessHandler {

    private LoginUserFilter loginUserFilter;

    public LogoutHandler(LoginUserFilter loginUserFilter){
        this.loginUserFilter = loginUserFilter;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (!Objects.isNull(authentication)){
            new SecurityContextLogoutHandler().logout(request,response,authentication);
        }
        String token = request.getHeader(Constant.User.ACCESS_TOKEN);
        if (!Objects.isNull(token)) {
            String username = this.username(token);
            if (!Objects.isNull(username)){
                RedisUtil.del(Constant.User.BACK_USER_KEY+username);
                RedisUtil.del(Constant.User.BACK_USER_TOKEN_KEY+username);
                RedisUtil.del(Constant.User.BACK_USER_PERMISSION_KEY+username);
            }
        }
        this.loginUserFilter.responseJson(response, R.ok(ResponseCode.SUCCESS.getMessage()));
    }

    /**
     * 从 token 获取 username
     * @param token
     * @return
     */
    private String username(String token){
        String username = "";
        try {
            Claims claims = JwtTokenUtil.parseToken(token);
            if (claims != null){
                username = (String) claims.get(Constant.User.JWT_USERNAME);
            }
        }catch (Exception ignored){}
        return username;
    }
}
